package com.gujia.controller;

import com.gujia.async.EventModel;
import com.gujia.async.EventProducer;
import com.gujia.async.EventType;
import com.gujia.model.Comment;
import com.gujia.service.CommentService;
import com.gujia.service.LikeService;
import com.gujia.util.AnswerUtil;
import com.gujia.util.EntityType;
import com.gujia.util.LoginUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * Created by GuJia on 2017/7/4.
 */
@Controller
public class LikeController {

    private static final Logger logger = LoggerFactory.getLogger(LikeController.class);

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private CommentService commentService;

    @RequestMapping(path={"/like"},method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String like(Model model, @RequestParam("commentId") int commentId){


        try{



            if(LoginUtil.getUser() == null) {
                return AnswerUtil.getJSONString(999);

            }

            Comment comment = commentService.getCommentById(commentId);

            eventProducer.fireEvent(new EventModel(EventType.LIKE)
                    .setActorId(LoginUtil.getUserId()).setEntityId(commentId)
                    .setEntityType(EntityType.ENTITY_COMMENT).setEntityOwerId(comment.getUserId())
                    .setExt("questionId", String.valueOf(comment.getEntityId())));

              long likeCount = likeService.like(LoginUtil.getUserId(),EntityType.ENTITY_COMMENT,commentId);
            return AnswerUtil.getJSONString(0,String.valueOf(likeCount));
        }catch (Exception e){
            e.printStackTrace();
            return AnswerUtil.getJSONString(1,"点赞失败！");

        }

    }

    @RequestMapping(path={"/dislike"},method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String disLike(Model model, @RequestParam("commentId") int commentId){


        try{



            if(LoginUtil.getUser() == null) {
                return AnswerUtil.getJSONString(999);

            }
            long disLikeCount = likeService.disLike(LoginUtil.getUserId(),EntityType.ENTITY_COMMENT,commentId);
            return AnswerUtil.getJSONString(0,String.valueOf(disLikeCount));
        }catch (Exception e){
            e.printStackTrace();
            return AnswerUtil.getJSONString(1,"点踩失败！");

        }

    }

}
